import type { RequestConfig,RunTimeLayoutConfig,RuntimeAntdConfig   } from '@umijs/max';
import {history} from '@umijs/max'
import { message,theme } from 'antd'
import store from 'store'
import {generateMenu} from '@/utils/router'
import service from '@/services/login/index'
import { getUserInfo,getTheme,THEME_VALUE } from '@/utils/index'
import HeaderRight from './components/HeaderRight';
import { loginOut,isLogin } from '@/utils/index';
import rightMenuLayout from './layouts/rightMenuLayout';


// 运行时配置
// 全局初始化数据配置，用于 Layout 用户信息和权限初始化
// 更多信息见文档：https://umijs.org/docs/api/runtime-config#getinitialstate
export async function getInitialState(): Promise<{ name: string,userInfo?:Partial<API.SaveLoginInt>,theme:THEME_VALUE }> {

  const theme = getTheme() || 'algor'

  return { name: '后台模板1',userInfo: getUserInfo(),theme};
}
export const layout:RunTimeLayoutConfig = ({initialState}) => {
  // console.log("initialState",initialState)
  return {
    title: '后台模板',
    logo: 'https://img.alicdn.com/tfs/TB1YHEpwUT1gK0jSZFhXXaAtVXa-28-27.svg',
    menu: {
      locale: false,
      // 每当 initialState?.currentUser?.userid 发生修改时重新执行 request
      params: {
        userid: initialState?.userInfo?.user_id,
      },
      
      request: async (params, defaultMenuData) => {
        try {
          const res = await service.LoginController.getMenuList({system_source:'cat'}) 
          const menuData = generateMenu({childlist:res.list})
          // console.log("menuData.routes-->",menuData.routes)
          return menuData.routes
        } catch (error) {
          return []
        }
       
      },

      

    },
    layout: 'mix',
    logout(initialState) {
      console.log('initialState',initialState)
      return service.LoginController.logout({system_source:'cat'})
    },
    rightRender(initialState, setInitialState, runtimeConfig) {
      return HeaderRight({})
    },
    
    menuRender(props, defaultDom) {
      return rightMenuLayout({renderDom:defaultDom,data:props});
    },


   
  };
};

const BASE_URL = '/api';
export const request:RequestConfig = {
  timeout: 5000,
  baseURL: BASE_URL,
  requestInterceptors: [
    (url, options) => {
      // 在请求头中添加token
      const token = store.get('token')
      if(token){
        options.headers = {
          ...options.headers,
          Token: token
        }
      }
      return {
        url,
        options: { ...options, interceptors: true },
      };
    },

  ],
  responseInterceptors: [
    // 直接写一个 function，作为拦截器
    (response) =>
      {
        // 不再需要异步处理读取返回体内容，可直接在data中读出，部分字段可在 config 中找到
        const { data = {} as any, config } = response;
        // do something
        return data
      },
    // 一个二元组，第一个元素是 request 拦截器，第二个元素是错误处理
    [
      (response) => {return response}, 
      (error:any) => {
        
        if(error?.response?.status === 401){
          loginOut()
          history.push('/login')
        }
      message.error(error?.response.data.msg)
      return Promise.reject(error)
    }],
    // 数组，省略错误处理
    [(response) => {return response}]
  ]
  
}

export function onRouteChange({ clientRoutes, location }) {
 console.log(clientRoutes, location)
 if(location.pathname === '/login' && isLogin()) {
    history.push('/')
 }
}


export const antd: RuntimeAntdConfig = (memo) => {
  console.log("memo",memo)
  memo.theme ??= {};
  const themeType = getTheme() || 'algor'
  memo.theme.algorithm = [themeType === 'drak'? theme.darkAlgorithm:theme.defaultAlgorithm]; // 配置 antd5 的预设 dark 算法
  // memo.appConfig = {
  //   message: {
  //     // 配置 message 最大显示数，超过限制时，最早的消息会被自动关闭
  //     maxCount: 3,
  //   },
    
  // }

  return memo;
};
